/**
 * Created by yang.fan on 2017/11/17.
 */
import React from 'react';
import {Modal, Button,Row,Col,Cascader,Input,Form,message} from 'antd';
import styles  from './BaiduMap.less';
import { request } from '../../config/request'
const { Component } = React
import { cloneDeep,isEqual } from 'lodash';
// 引入全局配置
import config from '../../config/config'
// 异步静态资源
import LoadAssets from 'load-assets'
import AdvanceSearch from '../CollapsiblePanels/AdvanceSearch'
import $ from 'jquery'
import reportIcon from "../../assets/img/dingweiweizhi-绿.png"; //report(报备)visit到访,sign签约,importIcon导入数据
import visitIcon from "../../assets/img/dingweiweizhi-蓝.png";
import signIcon from "../../assets/img/dingweiweizhi-黄.png";
import importIcon from "../../assets/img/dingweiweizhi-紫.png";

let count = 0, libs = [
  'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
  'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
  'https://api.map.baidu.com/library/Heatmap/2.0/src/Heatmap_min.js'
];
const head = document.getElementsByTagName('head')[0];
/*
 *
 * 地图组件
 *
 */

export default class Bmap extends Component {
    constructor(props) { //用于初始化state
      super(props);
   
      this.setMapRef = ref => {
        this.mapContainer = ref;
      };
      this.state = {
        markers:[],
        // 地图实例
        map: null,
        //开启关闭按钮
        visible: this.props.visible || false,
        markersData: this.props.markersData||[],//打点图数据
        heatmapData:this.props.heatmapData||[],//热力图数据
        mapType:this.props.mapType||'0',//地图类型 0.打点图 1.热力图
      }
    }
    // 组件挂载后调用
    // 可以在该函数中进行请求或者订阅
    componentDidMount() {
        if(!this.map){
          this.createMapScript().then(this.initMap);
        }
    }
    //父组件中改变了props传值时触发的函数
    componentWillReceiveProps(nextProps) {
      if(this.map){
        this.addOverlayGroup(nextProps)
      }else{
        //tabs切换 组件已销毁，但是地图资源已加载，不需要再次加载地图资源
        this.initMap()
      }
    
    }
    addOverlayGroup(payload){

      var _this = this

      let {map,maps,markerClusterer,heatmapOverlay} = _this
      let {markers} = _this.state
      var point = new BMap.Point(113.122717,23.028762);//佛山
      map.centerAndZoom(point,5)

      if(markerClusterer){
          markerClusterer.clearMarkers(markers)
          heatmapOverlay.hide()
          //打点图
        if(payload.markersData.length&&payload.mapType == '0'){
          markers = this.markerssFun(payload.markersData)
          //添加聚合点
          markerClusterer.addMarkers(markers)
        }
          //热力图
        if(payload.heatmapData.length&&payload.mapType == '1'){

          if(!this.isSupportCanvas()){
            alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
          }
          
          let hot_data =  payload.heatmapData.map((item,index)=>{
            return {
              lng: item.zituoLongitude,
              lat: item.zituoLatitude,
              count: item.count,
            }
          })
       
          heatmapOverlay.setDataSet({ data: hot_data, max: 100 });
          heatmapOverlay.show();
        }
  
      }else{
        markers = this.markerssFun(payload.markersData)
        // 第一次新增挂到全局
        //MarkerClusterer 首次 必须要先设置中心坐标点，否则报错，而且设置的坐标点必须是经纬度，不能够用名称去设置
        markerClusterer = new maps.MarkerClusterer(map, {markers:markers});
        heatmapOverlay = new maps.HeatmapOverlay({ radius: 20 });
        map.addOverlay(heatmapOverlay);
        _this.markerClusterer = markerClusterer
        _this.heatmapOverlay = heatmapOverlay
      }
      
      _this.setState({markers})
    }
    markerssFun(m){
      let markers = []
      for(var item of m){
        let pt = new BMap.Point(item.zituoLongitude,item.zituoLatitude)
        var myIcon;
        if (item.type == "0") {
          myIcon = new BMap.Icon(reportIcon, new BMap.Size(30, 30));
        } else if (item.type == "1") {
          myIcon = new BMap.Icon(visitIcon, new BMap.Size(30, 30));
        } else if (item.type == "2") {
          myIcon = new BMap.Icon(signIcon, new BMap.Size(30, 30));
        }else{
          myIcon = new BMap.Icon(importIcon, new BMap.Size(30, 30));
        }
        let marker = new BMap.Marker(pt, { icon: myIcon })
        markers.push(marker)
      }
      return markers
    }
    // 判断是否支持canvas
    isSupportCanvas(){
      var elem = document.createElement('canvas');
      return !!(elem.getContext && elem.getContext('2d'));
    }
    // 判断是否需要更新组件，多用于组件性能优化,使用后不会重新加载
    shouldComponentUpdate() {
      return !this.inited;
    }
    //组件挂载完成时触发的函数
    componentWillUnmount() {
      if (this.map) {
        this.map = null;
      }
      if (this.map) {
        this.maps = null
      }
      if(this.markerClusterer){
        this.markerClusterer = null
      }
    }
    initMap=()=>{

      let {BMap,BMapLib={}} = window
      
      // 百度地图API功能
      var map = new BMap.Map(this.mapContainer);
      var maps = BMapLib
      var point = new BMap.Point(113.122717,23.028762); //佛山

      map.centerAndZoom(point,5);
      map.setDefaultCursor('pointer');
      map.enableScrollWheelZoom();

      map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
      map.addControl(new BMap.NavigationControl());
     
      this.map = map
      this.maps = maps

    };
    createMapScript = () =>{
      var self = this
      const ak = 'ORYNu4GTZHUUg8uT4rXuzfDMxQNvGGY1';
      return new Promise((resolve, reject) => {
        if (window.BMap && Window.BMapLib) {
            // 已经加载则直接返回
            console.log('map already exist');
            resolve({BMap: window.BMap, BMapLib: window.BMapLib});
        } else {
            // 异步加载
            console.log('async load map');
            const bmap = document.createElement('script');
            bmap.type = 'text/javascript';
            bmap.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=MapLoadSuccess`;

            const bmapMeta = document.createElement('meta');
            bmapMeta['http-equiv'] = "Content-Security-Policy";
            bmapMeta['content']="upgrade-insecure-requests";

            head.appendChild(bmap);
            window.MapLoadSuccess = function() {
                // BMap加载完成，开始加载libs
                libs.forEach(lib => {
                  self.loadLib(lib, resolve, reject);
                })
            }
            bmap.onerror = function() {
                reject('地图初始化失败');
            }
        }
    })
    }

    loadLib(src, resolve, reject) {
      const lib = document.createElement('script');
      lib.setAttribute('type', 'text/javascript');
      lib.setAttribute('src', src);
      lib.onerror = function() {
          reject('地图初始化失败');
      }
      lib.onload = function() {
          count += 1;
          if (count === libs.length) { // libs全部加载成功才返回
              resolve({BMap: window.BMap, BMapLib: window.BMapLib});
          }
      }
      head.appendChild(lib);
  }
  
    render() {
      const { width = '100%', height = 700, style } = this.props;
  
      return (
        <div style={{ border: 'solid 1px #e1e1e1', marginBottom: 16, borderRadius: 5 }}>
          <div ref={this.setMapRef} style={{ width, height, ...style }} />
        </div>
      );
    }
  }


